package com.dy.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dy.domain.Dishes;
import com.dy.mapper.DishesMapper;
import com.dy.utils.JsonResultUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/dishesAddServlet")
public class DishesAddServlet extends HttpServlet {
    public DishesAddServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码类型
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String dname = request.getParameter("dname");
        Double price = Double.valueOf(request.getParameter("price"));
        Double discount = Double.valueOf(request.getParameter("discount"));
        String img = request.getParameter("img");

        //1. 加载mybatis的核心配置文件，获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.1 获取UserMapper接口的代理对象
        DishesMapper dishesMapper = sqlSession.getMapper(DishesMapper.class);
        Dishes dishes = new Dishes();
        dishes.setDname(dname);
        dishes.setPrice(price);
        dishes.setDiscount(discount);
        dishes.setImg(img);
        dishesMapper.add(dishes);

        sqlSession.commit();
        sqlSession.close();

        JSONObject data = JsonResultUtil.getJson(0,1,"请求成功");
        response.getWriter().print(data);
    }
}
